from django.http import JsonResponse
from django.db.models import Q
from .models import Data

def query_data(request):
    search_keyword = request.POST.get('search', '')
    if search_keyword:
        # 使用Q对象进行模糊查询，可以根据需要调整查询字段和条件
        results = Data.objects.filter(Q(name__icontains=search_keyword) | Q(description__icontains=search_keyword))
        # 将查询结果转换为字典列表
        result_list = [{"name": item.name, "description": item.description} for item in results]
        return JsonResponse(result_list, safe=False)
    else:
        return JsonResponse({"error": "请输入搜索关键词"}, status=400)

def add_data_view(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description')
        # 创建对象并保存到数据库
        MyModel.objects.create(name=name, description=description)
        return JsonResponse({'status': 'success'})